package com.lakers.notice.springboot.monitor;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.lakers.notice.springboot.condition.ConditionalOnMonitor;
import com.lakers.notice.springboot.model.NoticeTerminalType;
import com.lakers.notice.springboot.netty.UserChannelCtxMap;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.Map;
import java.util.Objects;
import java.util.StringJoiner;

/**
 * 功能描述: MThreadChannel
 *
 * @author liqin(zxl)
 * @date 2024/5/13
 */
@Component
@ConditionalOnMonitor
@Slf4j
public class MThreadChannel implements InitializingBean {

    private static Thread MONITOR_THREAD = null;

    @Override
    public void afterPropertiesSet() {
        MONITOR_THREAD = ThreadUtil.newThread(() -> {
            while (true){
                try {
                    Thread.sleep(1000);
                }catch (Throwable ignored){

                }
                final Map<String, Map<Integer, ChannelHandlerContext>> all = UserChannelCtxMap.getAll();
                if (MapUtil.isEmpty(all)){
                    continue;
                }
                for (Map.Entry<String, Map<Integer, ChannelHandlerContext>> entry : all.entrySet()) {
                    final String userId = entry.getKey();
                    final Map<Integer, ChannelHandlerContext> channelIds = entry.getValue();
                    StringJoiner js = new StringJoiner(StrUtil.COMMA);
                    js.add(String.format("online user is: %s ", userId));
                    for (Map.Entry<Integer, ChannelHandlerContext> channel : channelIds.entrySet()) {
                        final NoticeTerminalType terminalType = NoticeTerminalType.fromCode(channel.getKey());
                        js.add(String.format("device is: %s ", Objects.isNull(terminalType) ? null: terminalType.name()));
                        js.add(String.format("channel id is: %s ", channel.getValue().channel().id().asLongText()));
                    }
                    log.info(js.toString());
                }
            }
        }, "MONITOR USER THREAD");
        MONITOR_THREAD.start();
    }

    @PreDestroy
    public void destroy(){
       if (Objects.nonNull(MONITOR_THREAD) && MONITOR_THREAD.isAlive()){
           MONITOR_THREAD. interrupt();
       }
    }
}
